/**
 * @function request
 * @param {IParams} 参数
 * @return {Promise} 返回Promise对象
 * @description 封装uniapp的request
 * @author zhaoyongqiang
 *
 */

interface IParams {
	url?: string;
	api: string;
	method?: 'get' | 'post' | 'put' | 'delete' | 'connect' | 'head' | 'options' | 'trace';
	header?: Record<string, string>; // 新增自定义 headers 参数
	data?: any;
	formData?: true | false;
	dataType?: 'json' | '';
	timeout?: number;
	responseType?: 'arraybuffer' | 'text';
	sslVerify?: true | false;
	withCredentials?: true | false;
	firstIpv4?: true | false;
	enableHttp2?: true | false;
	enableQuic?: true | false;
	enableCache?: true | false;
	enableHttpDNS?: true | false;
	httpDNSServiceId?: string;
	enableChunked?: true | false;
	forceCellularNetwork?: true | false;
	enableCookie?: true | false;
	cloudCache?: true | false;
	defer?: true | false;
	auth?: true | false;
}

export function request({
	url = getApp().globalData.baseUrl,
	api,
	method = 'get',
	header,
	data,
	formData = false,
	auth = true,
	dataType = 'json',
	timeout = 60000,
	responseType = 'text',
	sslVerify = true,
	withCredentials = false,
	enableHttp2 = false,
	enableQuic = false,
	enableCache = false,
	enableHttpDNS = false,
	httpDNSServiceId = undefined,
	enableChunked = false,
	forceCellularNetwork = false,
	enableCookie = false,
	cloudCache = false,
	defer = false
}: IParams): Promise<any> {
	return new Promise((resolve, reject) => {
		// 1. 生成全局 header
		const baseHeader = getApp().globalData.setHeader(url, auth, formData);
		// 2. 根据用户是否传入 header 参数决定最终 header
		const finalHeader = header !== undefined ? header : baseHeader;
		// 3. 处理请求数据，自动添加accessToken到form data中
		const processedData = getApp().globalData.processRequestData(data, auth);
		
		const currentParams = {
			url,
			api,
			method,
			header,
			data: processedData, // 使用处理过的数据
			formData,
			dataType,
			timeout,
			responseType,
			sslVerify,
			withCredentials,
			enableHttp2,
			enableQuic,
			enableCache,
			enableHttpDNS,
			httpDNSServiceId,
			enableChunked,
			forceCellularNetwork,
			enableCookie,
			cloudCache,
			defer,
			auth
		};
		const normalizedMethod = method.toUpperCase() as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'HEAD' | 'OPTIONS' | 'TRACE';
		uni.request({
			url: url + api,
			method: normalizedMethod,
			header: finalHeader,
			data: processedData,
			dataType,
			timeout,
			responseType,
			sslVerify,
			withCredentials,
			enableHttp2,
			enableQuic,
			enableCache,
			enableHttpDNS,
			httpDNSServiceId,
			enableChunked,
			forceCellularNetwork,
			enableCookie,
			cloudCache,
			defer,
			success: (res) => {
				if (getApp().globalData.httpSuccessCodes.includes(res.statusCode)) {
					const errorMsg = getApp().globalData.systemError(res.data);
					if (errorMsg === undefined) {
						resolve(res.data); // 正常响应
					}  else {
						reject(errorMsg); // 其他业务错误
					}
				}  else {
					// 服务器错误处理
					reject('服务器错误');
					uni.showToast({ title: '服务器错误', icon: 'error', duration: 2500 });
				}
			},
			fail: (err) => {
				// 请求失败 timeout 或者无网络等 域名错误等
				reject(err.errMsg);
				uni.showToast({
					title: '无法连接到服务器',
					icon: 'error',
					duration: 2500
				});
			}
		});
	});
}
